<!--
/**
* Copyright (C) 2022-2023 Timber Chain Cloud (TimberCLD). All Rights Reserved.
* 
* @author: luoweijian
* @email: 807301075@qq..com
* @site: https://www.timbercld.com/
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* 
* http://www.apache.org/licenses/LICENSE-2.0
* 
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
*  limitations under the License.
*/
-->
<template>
  <el-dialog v-model="options.visible" :title="!formData.id ? t('add') : t('update')" :close-on-click-modal="false" :close-on-press-escape="false" :closed="resetDataForm">
    <el-form v-loading="options.loading" :model="formData" :rules="formRules" ref="formRef" @keyup.enter="submitDataFormHandle()" label-width="180px">
      <el-form-item prop="productName" :label="t('product.productName')">
        <el-input v-model="formData.productName" :placeholder="t('product.productName')"></el-input>
      </el-form-item>
      <el-form-item prop="marks" :label="t('product.marks')">
        <el-input type="textarea" v-model="formData.marks" :placeholder="t('product.marks')"></el-input>
      </el-form-item>
      <el-form-item prop="price" :label="t('product.price')">
        <el-input v-model="formData.price" :placeholder="t('product.price')"></el-input>
      </el-form-item>
      <el-form-item prop="pic" :label="t('product.pic')" v-loading="options.uploadImageLoading">
        <el-upload
          action="#"
          ref="uploadRef"
          list-type="picture-card"
          :file-list="fileList"
          :on-remove="handleRemove"
          :http-request="handleUpload"
          :auto-upload="true"
          :limit="1"
          :on-preview="handlePictureCardPreview"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="options.visible = false">{{ t('cancel') }}</el-button>
      <el-button type="primary" @click="submitDataFormHandle()">{{ t('confirm') }}</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="options.previewVisible" :title="t('product.preview')" append-to-body>
    <img :src="options.previewImgUrl" style="background-color: rgb(0, 0, 0); width: 100%" />
  </el-dialog>
</template>

<script setup lang="ts">
import _ from 'lodash';
import { useI18n } from 'vue-i18n';
import http from '@/utils/request';
import { productApi } from '@/api/product';
import { uploadImgEcho } from '@/utils';
import type { ResType } from '@/utils/request';
import debounce from 'lodash/debounce';
import { FormRules, ElMessage } from 'element-plus';
import { ref, reactive, nextTick, watch } from 'vue';
import type { ElForm, UploadProps, UploadUserFile } from 'element-plus';

// #region 类型
interface FileValue {
  url?: string;
}
interface FormData {
  id: string;
  productName: string;
  marks: string;
  price: string;
  pic: string;
  fileObj: FileValue;
}

// #endregion

// #region 属性
const emit = defineEmits<{
  refreshPageHandle: [];
}>();
const { t } = useI18n();

const formRef = ref<InstanceType<typeof ElForm> | null>(null);

const dialogId = ref('0');
const uploadRef = ref();

// 表单数据
const formData = reactive<FormData>({
  id: '',
  productName: '',
  marks: '',
  price: '',
  pic: '',
  fileObj: {},
});
// 页面配置
const options = reactive({
  visible: false,
  loading: false,
  previewVisible: false,
  previewImgUrl: '',
  uploadImageLoading: false,
  uploadUrl: `${window.SITE_CONFIG.apiURL}/timbercld/demo/product/upload/`,
});
const fileList = ref<UploadUserFile[]>([]);

// #region 自定义规则
const validatePic = (rule: any, value: any, callback: any) => {
  if (formData.pic === null || !formData.pic) {
    return callback(new Error(t('validate.required')));
  }
  callback();
};
// #endregion
// 验证规则
const formRules = reactive<FormRules<FormData>>({
  productName: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  marks: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  price: [{ required: true, message: t('validate.required'), trigger: 'blur' }],
  pic: [{ required: true, message: t('validate.required'), validator: validatePic, trigger: 'blur' }],
});
// #endregion

// #region 方法
watch([() => dialogId.value], (val1) => {
  formData.id = val1[0];
});

const resetDataForm = () => {
  formRef.value?.resetFields();
  uploadRef.value?.clearFiles();
  fileList.value = [];
  formData.fileObj = {};
  options.previewImgUrl = '';
};
async function init() {
  options.visible = true;
  resetDataForm();
  await nextTick();
  if (formData.id) {
    getInfo();
  }
}
// 获取信息
const getInfo = () => {
  options.loading = true;
  productApi.getProductInfo(formData.id).then((res) => {
    if (res?.code === 0) {
      nextTick(() => {
        Object.assign(formData, res.data);
        console.log('formData--->', formData);
        uploadImgEcho(formData.pic, uploadRef.value);
      });
    } else {
      ElMessage.error(res.msg);
    }
    setTimeout(() => {
      options.loading = false;
    }, 500);
  });
};

const handleUpload = async (e: any) => {
  console.log('e--->', e);

  options.uploadImageLoading = true;
  const submitData = new FormData();
  submitData.append('file', e.file);
  submitData.append('fileName', e.file.name.substring(0, e.file.name.lastIndexOf('.')));

  http
    .post(options.uploadUrl, submitData)
    .then((res) => {
      if (res?.code === 0) {
        formData.fileObj.url! = res.data as string;
        formData.pic = res.data as string;
        ElMessage({
          type: 'success',
          message: '上传成功',
          duration: 500,
        });
      } else {
        ElMessage.error(res.msg);
      }
      setTimeout(() => {
        options.uploadImageLoading = false;
      }, 500);
    })
    .catch((err) => {
      ElMessage.error(err.msg);
      options.uploadImageLoading = false;
    });
};
const handleRemove = () => {
  formData.pic = '';
};

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  options.previewImgUrl = uploadFile.url!;
  options.previewVisible = true;
};

// 新增商品
function insertSub() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    productApi
      .insertProduct(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 更新商品
function updateSub() {
  return new Promise<ResType<unknown>>((resolve, reject) => {
    productApi
      .updateProduct(formData)
      .then((res) => {
        resolve(res);
      })
      .catch((err) => [reject(err)]);
  });
}
// 表单提交
function submit() {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      console.log('formData--->', formData);

      options.loading = true;
      let res;
      // if (formData.id) {
      //   res = await updateSub();
      // } else {
      //   res = await insertSub();
      // }
      // if (res?.code !== 0) {
      //   ElMessage.error(res.msg);
      // } else {
      //   ElMessage.success(t('prompt.success'));
      //   options.visible = false;
      //   emit('refreshPageHandle');
      // }
    }
  });
}

const submitDataFormHandle = debounce(submit, 1000, { leading: true, trailing: false });

defineExpose({
  init,
  dialogId,
});
// #endregion
</script>
